package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class SearchProductsServlet extends HttpServlet {

    private final static String SEARCH_PRODUCT =  "/WEB-INF/jsp/catalog/searchProducts.jsp";

    private final static String ERROR_FORM =  "/WEB-INF/jsp/common/error.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String keyword = req.getParameter("keyword");
        HttpSession session = req.getSession();
        if (keyword != null && keyword.length() >= 1) {
            CatalogService catalogService = new CatalogService();
            List<Product>productList = catalogService.searchProductList(keyword.toLowerCase());
            session.setAttribute("productList",productList);
            req.getRequestDispatcher(SEARCH_PRODUCT).forward(req,resp);
        } else {
            session.setAttribute("errorMsg","Please enter a keyword to search for, then press the search button.");
            req.getRequestDispatcher(ERROR_FORM).forward(req,resp);
        }
    }
}
